package com.rf.richfitwheel.admin.sys.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rf.richfitwheel.admin.sys.dao.*;
import com.rf.richfitwheel.admin.sys.model.*;
import com.rf.richfitwheel.admin.sys.service.ConfigService;
import com.rf.richfitwheel.admin.sys.service.SysRoleMenuService;
import com.rf.richfitwheel.admin.sys.service.SysRoleService;
import com.rf.richfitwheel.admin.sys.service.SysUserRoleService;
import com.rf.richfitwheel.admin.sys.vo.UserVO;
import com.rf.richfitwheel.common.contants.Constant;
import com.rf.richfitwheel.common.exception.BusinessException;
import com.rf.richfitwheel.common.utils.PageUtils;
import com.rf.richfitwheel.common.utils.StringUtils;
import com.rf.richfitwheel.common.utils.UuidUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.*;

/**
 * 角色
 *
 * @author hushouquan
 * @date 2020年4月18日 上午9:45:12
 */
@Service("sysRoleService")
public class SysRoleServiceImpl implements SysRoleService {
    
    public static final String BUSINESS_ADMIN_ROLE_IDS = "BUSINESS_ADMIN_ROLE_IDS";
    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private SqlAdapterMapper sqlAdapterMapper;//注入dao
    @Autowired
    private OrgMapper orgMapper;
    @Autowired
    private ConfigService configService;

    /**
     * 分页查询
     *
     * @param params 参数
     * @param userVO 操作用户
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params, UserVO userVO) {
        PageUtils pageUtils = PageUtils.getPageInfo(params);
        Page<Role> p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
//        Page<Object> p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
        RoleExample example = new RoleExample();
        RoleExample.Criteria criteria = example.createCriteria();
//        Map<String, Object> paramsNew = new HashMap<String, Object>();
        JSONObject parObj = JSONObject.fromObject(params.get("dataForm"));
        if (parObj.get("roleName") != null && !"".equals(parObj.get("roleName"))) {
//            paramsNew.put("roleName", "%" + parObj.get("roleName").toString() + "%");
            criteria.andRoleNameLike("%" + parObj.get("roleName").toString() + "%");
        }
        if (parObj.get("moduleType") != null && !"".equals(parObj.get("moduleType"))) {
//            paramsNew.put("moduleType", "%" + parObj.get("moduleType").toString() + "%");
            criteria.andModuleTypeEqualTo(parObj.get("moduleType").toString());
        }
//        List<Map<String, Object>> list = MapCaseUtil.mapKeyToLowerCase(roleMapper.selectByParams(paramsNew));
        roleMapper.selectByExample(example);
        pageUtils = new PageUtils(p);
//        pageUtils.setList(list);
        return pageUtils;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(Role role) {
        role.setCreateTime(new Date());
//        this.insert(role);

        //检查权限是否越权
        checkPrems(role);

        //保存角色与菜单关系
//        sysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(Role role) {
//        this.updateById(role);

        //检查权限是否越权
        checkPrems(role);

        //更新角色与菜单关系
//        sysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteBatch(String[] roleIds) throws Exception {
        for (String roleId : roleIds) {
            //删除角色
            roleMapper.deleteByPrimaryKey(roleId);

            //删除角色与菜单关联
            RoleMenuExample example = new RoleMenuExample();
            RoleMenuExample.Criteria criteria = example.createCriteria();
            criteria.andRoleIdEqualTo(roleId);
            roleMenuMapper.deleteByExample(example);

            //删除角色与用户关联
            UserRoleExample exampleUserRole = new UserRoleExample();
            UserRoleExample.Criteria criteriaUserRole = exampleUserRole.createCriteria();
            criteriaUserRole.andRoleIdEqualTo(roleId);
            userRoleMapper.deleteByExample(exampleUserRole);
        }

    }

    @Override
    public List<Long> queryRoleIdList(Long createUserId) {
        return null;//baseMapper.queryRoleIdList(createUserId);
    }

    /**
     * 检查权限是否越权
     */
    private void checkPrems(Role role) {
        //如果不是超级管理员，则需要判断角色的权限是否超过自己的权限
//		if(role.getCreateUserId() == Constant.SUPER_ADMIN){
//			return ;
//		}

        //查询用户所拥有的菜单列表
//		List<Long> menuIdList = sysUserService.queryAllMenuId(role.getCreateUserId());

        //判断是否越权
//		if(!menuIdList.containsAll(role.getMenuIdList())){
////			throw new RRException("新增角色的权限，已超出你的权限范围");
//		}
    }

    /* （非 Javadoc）
     * getResTreeByRoleId
     * @param id
     * @return
     * @see com.rf.richfitwheel.admin.sys.service.SysRoleService#getResTreeByRoleId(java.lang.String)
     */
    @Override
    public List<RoleMenu> getResTreeByRoleId(String id) {
        RoleMenuExample example = new RoleMenuExample();
        RoleMenuExample.Criteria criteria = example.createCriteria();
        criteria.andRoleIdEqualTo(id);
        return roleMenuMapper.selectByExample(example);
    }

    /* （非 Javadoc）
     * selectById
     * @param roleId
     * @return
     * @see com.rf.richfitwheel.admin.sys.service.SysRoleService#selectById(java.lang.Long)
     */
    @Override
    public Role selectById(String roleId) {
        return roleMapper.selectByPrimaryKey(roleId);
    }

    /* （非 Javadoc）
     * save
     * @param role
     * @param user
     * @see com.rf.richfitwheel.admin.sys.service.SysRoleService#save(com.rf.richfitwheel.admin.sys.model.Role, com.rf.richfitwheel.admin.sys.model.User)
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(Role role, UserVO userVO) throws Exception {
        RoleExample example = new RoleExample();
        RoleExample.Criteria criteria = example.createCriteria();
        criteria.andModuleTypeEqualTo(role.getModuleType());
        criteria.andRoleNameEqualTo(role.getRoleName().trim());
        List<Role> roleHas = roleMapper.selectByExample(example);
        if(!roleHas.isEmpty()){
            throw new BusinessException("角色名称在所属模块已存在");
        }
        Date date = new Date();
        role.setId(UuidUtil.get32UUID());
        role.setCreateUserId(userVO.getId());
        role.setCreateTime(date);
        role.setModTime(date);
        role.setModUserId(userVO.getId());
        roleMapper.insert(role);
        for (String resid : role.getResId()) {
            RoleMenu rm = new RoleMenu();
            rm.setId(UuidUtil.get32UUID());
            rm.setMenuId(resid);
            rm.setRoleId(role.getId());
            roleMenuMapper.insert(rm);
        }
    }

    /* （非 Javadoc）
     * update
     * @param role
     * @param user
     * @throws Exception
     * @see com.rf.richfitwheel.admin.sys.service.SysRoleService#update(com.rf.richfitwheel.admin.sys.model.Role, com.rf.richfitwheel.admin.sys.model.User)
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Role role, UserVO userVO) throws Exception {
        RoleExample example = new RoleExample();
        RoleExample.Criteria criteria = example.createCriteria();
        criteria.andModuleTypeEqualTo(role.getModuleType());
        criteria.andRoleNameEqualTo(role.getRoleName().trim());
        criteria.andIdNotEqualTo(role.getId());
        List<Role> roleHas = roleMapper.selectByExample(example);
        if(!roleHas.isEmpty()){
            throw new BusinessException("角色名称在所属模块已存在");
        }
        Date date = new Date();
        role.setModTime(date);
        role.setModUserId(userVO.getId());
        roleMapper.updateByPrimaryKeySelective(role);
        //先删除角色资源关联再增加，非超级管理员只能删除自己租户的角色资源
        RoleMenuExample example1 = new RoleMenuExample();
        RoleMenuExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andRoleIdEqualTo(role.getId());
        roleMenuMapper.deleteByExample(example1);
        for (String resid : role.getResId()) {
            RoleMenu rm = new RoleMenu();
            rm.setId(UuidUtil.get32UUID());
            rm.setMenuId(resid);
            rm.setRoleId(role.getId());
            roleMenuMapper.insert(rm);
        }
    }

    /* （非 Javadoc）
     * setRoleMenu
     * @param role
     * @param user
     * @see com.rf.richfitwheel.admin.sys.service.SysRoleService#setRoleMenu(com.rf.richfitwheel.admin.sys.model.Role, com.rf.richfitwheel.admin.sys.model.User)
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setRoleMenu(Role role, UserVO userVO) {
        //先删除角色资源关联再增加，非超级管理员只能删除自己租户的角色资源
        RoleMenuExample example = new RoleMenuExample();
        RoleMenuExample.Criteria criteria = example.createCriteria();
        criteria.andRoleIdEqualTo(role.getId());
        roleMenuMapper.deleteByExample(example);

        for (String resid : role.getResId()) {
            RoleMenu rm = new RoleMenu();
            rm.setId(UuidUtil.get32UUID());
            rm.setMenuId(resid);
            rm.setRoleId(role.getId());
            roleMenuMapper.insert(rm);
        }
    }

    /* （非 Javadoc）
     * queryRserRoleList
     * @param roleId
     * @return
     * @see com.rf.richfitwheel.admin.sys.service.SysRoleService#queryRserRoleList(java.lang.String)
     */
    @Override
    public PageUtils queryUserRoleList(Map<String, Object> params) {
        PageUtils pageUtils = PageUtils.getPageInfo(params);
        Page<Map<String, Object>> p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
        String roleId = params.get("roleId") == null ? "" : params.get("roleId").toString();
        List<Map<String, Object>> list = userRoleMapper.selectByRoleId(roleId);
        pageUtils = new PageUtils(p);
        return pageUtils;
    }

    /**
     * 获取有效用户，不包含员工及已添加的用户，只能选择当前角色租户下的用户
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryUserRoleNoChooseList(Map<String, Object> params, UserVO userVO) {
        String roleId = params.get("roleId") == null ? "" : params.get("roleId").toString();
        Role role = roleMapper.selectByPrimaryKey(roleId);//这个放在前面，否则分页有问题
        PageUtils pageUtils = PageUtils.getPageInfo(params);
        Page<Map<String, Object>> p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
        JSONObject dataForm = JSONObject.fromObject(params.get("dataForm"));
        String staffName = null;
        String orgName = null;
        if (dataForm != null && StringUtils.isNotBlank(dataForm.get("staffName"))) {
            staffName = "%" + dataForm.getString("staffName") + "%";
        }
        if (dataForm != null && StringUtils.isNotBlank(dataForm.get("orgName"))) {
            orgName = "%" + dataForm.getString("orgName") + "%";
        }
        Map<String, String> queryPra = new HashMap<String, String>();
		/*if(!user.getTenantId().equals(Constant.SUPER_ADMIN_TENANTID)) {
			queryPra.put("tenantId", user.getTenantId());
		}*/
        queryPra.put("tenantId", role.getTenantId());
        queryPra.put("roleId", roleId);
        queryPra.put("staffName", staffName);
        queryPra.put("orgName", orgName);
        queryPra.put("status", Constant.USER_STATUS_NORMAL);
        List<Map<String, Object>> list = userRoleMapper.selectByRoleIdNoChoose(queryPra);
        pageUtils.setList(list);
        pageUtils = new PageUtils(p);
        return pageUtils;
    }

    /* （非 Javadoc）
     * setSysRoleUser
     * @param userId
     * @param roleId
     * @param user
     * @see com.rf.richfitwheel.admin.sys.service.SysRoleService#setSysRoleUser(java.lang.String, java.lang.String, com.rf.richfitwheel.admin.sys.model.User)
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setSysRoleUser(String userId, String roleId, UserVO userVO) {
        UserRole record = new UserRole();
        record.setId(UuidUtil.get32UUID());
        record.setRoleId(roleId);
        record.setUserId(userId);
        userRoleMapper.insert(record);
    }

    /* （非 Javadoc）
     * deleteSysRoleUser
     * @param id
     * @param user
     * @see com.rf.richfitwheel.admin.sys.service.SysRoleService#deleteSysRoleUser(java.lang.String, com.rf.richfitwheel.admin.sys.model.User)
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSysRoleUser(String id, User user) {
        userRoleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<RoleMenu> getResTreeByRoleIdAndModuleType(String id, String moduleType) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("moduleType", moduleType);
        map.put("roleId", id);
        return roleMenuMapper.getResTreeByRoleIdAndModuleType(map);
    }

    @Override
    public List<Role> getRoleByParams(Map<String, Object> params) {
        RoleExample example = new RoleExample();
        RoleExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(params.get("moduleType"))) {
            criteria.andModuleTypeEqualTo(params.get("moduleType").toString());
        }
        List<Role> list = roleMapper.selectByExample(example);
        return list;
    }


    @Override
    public List<Role> getRoleList(Map<String, Object> params, UserVO user) {
        RoleExample example = new RoleExample();
        RoleExample.Criteria criteria = example.createCriteria();
        if (params.containsKey("includeAdmin")) {
            String includeAdmin = (String) params.get("includeAdmin");
            if ("1".equals(includeAdmin)) {

            } else {
                Config config = configService.getParamVlueByKey(BUSINESS_ADMIN_ROLE_IDS);
                List<String> idList = new ArrayList<>();
                if (config != null) {
                    idList = Arrays.asList(config.getParamValue().trim().split(","));
                }
                if(idList.isEmpty()){
                    idList.add("1");
                    idList.add("714d7011f0f34ffe8cee300fa9f9b395");
                    idList.add("5915ea7da18f4a0493186ee6c3c347e4");
                    //结算的集团管理员
                    idList.add("bd38f687eea94376b68de511d3e588eb");
                    //给财务公司使用的管理员
                    idList.add("30ea153536cd4574927e4ac0c8684ca6");
                }
                criteria.andIdNotIn(idList);
            }
        }
        if (params.containsKey("moduleType")) {
            String moduleType = (String) params.get("moduleType");
            if(StringUtils.isNotBlank(moduleType)){
                List<String> modList = new ArrayList<>(Arrays.asList(moduleType.split(",")));
                modList.add(Constant.SystemModule.sys.name());
                criteria.andModuleTypeIn(modList);
            }
        }
        List<Role> roles = roleMapper.selectByExample(example);
        return roles;
    }

    @Override
    public JSONArray getRoleDataByUserId(String userId) {
        UserRoleExample exampleUserRole = new UserRoleExample();
        UserRoleExample.Criteria criteriaUserRole = exampleUserRole.createCriteria();
        criteriaUserRole.andUserIdEqualTo(userId);
        List<UserRole> list = userRoleMapper.selectByExample(exampleUserRole);
        JSONArray jsonArrayByRole = new JSONArray();
        if (list.size() > 0) {
            Set<String> userRoleOrgIdSet = new HashSet<String>();
            for (UserRole userRole : list) {
                userRoleOrgIdSet.add(userRole.getOrgId());
            }
            for (String userRoleOrgId : userRoleOrgIdSet) {
                Org org = orgMapper.selectByPrimaryKey(userRoleOrgId);
                Org parentOrg = orgMapper.selectByPrimaryKey(org.getParentId());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("orgId", userRoleOrgId);
                jsonObject.put("orgName", parentOrg.getOrgName() + "---" + org.getOrgName());
                JSONArray jsonArray = new JSONArray();
                for (UserRole userRole : list) {
                    if (userRoleOrgId.equals(userRole.getOrgId())) {
                        Role role = roleMapper.selectByPrimaryKey(userRole.getRoleId());
                        JSONObject json = new JSONObject();
                        json.put("id", userRole.getId());
                        json.put("roleId", userRole.getRoleId());
                        json.put("moduleType", role.getModuleType());
                        jsonArray.add(json);
                    }
                }
                jsonObject.put("roleData", jsonArray);
                jsonArrayByRole.add(jsonObject);
            }
        }
        return jsonArrayByRole;
    }

    @Override
    public boolean checkRoleName(String moduleType, String roleName) {
        Role role = this.getRoleByModeuleTypeAndRoleName(moduleType, roleName);
        if (ObjectUtils.isEmpty(role)) {
            return false;
        }
        return true;
    }

    @Override
    public Role getRoleByModeuleTypeAndRoleName(String moduleType, String roleName) {
        RoleExample example = new RoleExample();
        RoleExample.Criteria criteriaUserRole = example.createCriteria();
        criteriaUserRole.andModuleTypeEqualTo(moduleType);
        criteriaUserRole.andRoleNameEqualTo(roleName);
        List<Role> list = roleMapper.selectByExample(example);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

}
